<template>
  <van-index-bar :index-list="computedList" @select="changeHander">
    <div v-for="city in cityList" :key="city.type">
      <van-index-anchor :index="city.type"/>
      <van-cell v-for="item in city.list" :title="item.name" :key="item.cityId" @click="handeAdd(item)"/>
    </div>
  </van-index-bar>
</template>
<script>
import { Toast } from 'vant';
import http from '@/util/http'
import {mapState,mapMutations} from 'vuex'
import obj from '@/util/mixin0bj'
export default {
  mixins:[obj],
  computed:{
    ...mapState(['cityList','cityName']),
    computedList(){
      return this.cityList.map(item=>item.type)
    }
  },
  mounted () {
    // 判断并发送请求
    if(this.cityList.length === 0){
      http({
        url: '/gateway?k=788351',
        headers: {
          'X-Host': 'mall.film-ticket.city.list'
        }
      }).then(res => {
        this.randerList(res.data.data.cities)
      })
    }
  },
  // 离开组件打开footer
  methods: {
    ...mapMutations(['changeCityList','changeCity','clearAll']),
    randerList (list) {
      // 26个首字母
      const letterList = []
      for (let i = 65; i < 91; i++) {
        letterList.push(String.fromCharCode(i))
      }
      const cityList = []
      letterList.forEach(letter => {
        // 过滤首字母
        const newlist = list.filter(item => item.pinyin.substring(0, 1).toUpperCase() === letter)
        newlist.length > 0 && cityList.push({
          type: letter,
          list: newlist
        })
      })
      this.changeCityList(cityList)
    },
    changeHander(item){
      Toast.setDefaultOptions({ duration: 500 });
      Toast(item)
    },
    handeAdd(item){
      /*多页面跳转
        location.href="/cinema?cityname="+item.name
        储存在cookie localStorage中，用时取

        单页面方案
        中间人模式
        bus事件总线 $on $emit

        vuex 状态管理模式 管理多个状态，多个地方都可以使用
        this.$store.state.cityId = item.cityId
        直接修改出了bug无法调试
      */
      // 解决bug: 两次地址相同，使用缓存,而不刷新
      if (item.name === this.cityName){
        this.$router.back();
        return
      }
      // 更改城市缓存
      this.changeCity(item)
      // 将原来的缓存清空
      this.clearAll()
      // 返回原来页面
      this.$router.back()
    }
  }
}
</script>
<style>
.van-index-bar__index{
  font-size: 2rem;
  line-height: 2.5rem;
}
.van-index-anchor{
  font-size: 3rem;
  background: rgb(248, 246, 246);
}
.van-toast--html, .van-toast--text{
  min-width: 2.5rem;
}
</style>
